import { defineStore } from "pinia";
import type { FormInstance, FormRules } from 'element-plus'
import router from "@/router";
import request from "@/plugins/request";

export const useRegisterStore = defineStore('RegisterStore', () => {
    const ruleFormRef = ref()
    const userRegisterForm = reactive({
        username: '',
        password: '',
        checkPassword: '',
        telephone: ''
    })

    // 正则表达式规则
    const reg_username: RegExp = /^[a-zA-Z0-9]{3,8}$/ // 数字或字母混合3-8位
    const reg_password: RegExp = /^[a-zA-Z0-9]{6,16}$/ // 数字或字母混合4-16位
    const reg_phone: RegExp = /^1[3456789]\d{9}$/ // 手机号正则表达式

    // 校验密码
    const validatePass2 = (rule: any, value: any, callback: Function) => {
        { rule }
        if (value !== userRegisterForm.password) {
            return callback(new Error('两次密码必须相同'))
        } else {
            callback()
        }
    }

    // 规则
    const rules = reactive<FormRules<typeof userRegisterForm>>({
        username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
            { pattern: reg_username, message: '用户名格式不正确' }
        ],
        password: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { pattern: reg_password, message: '密码格式不正确' }
        ],
        checkPassword: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { pattern: reg_password, message: '密码格式不正确' },
            { validator: validatePass2, trigger: 'blur' }
        ],
        telephone: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { pattern: reg_phone, message: '手机号格式不正确' }
        ],
    })

    // 提交
    function submitForm(formEl: FormInstance | undefined) {
        if (!formEl) return
        // 这里【注意】使用表单组件中的validate时，如果回调函数内部发生了错误，会激活重新校验，这时的valid值就会为false
        formEl.validate(async (valid) => {
            if (valid) {
                // 处理数据，发送请求
                const { data: result } = await request.post('/userInfo/register', userRegisterForm)
                if (result.code === 200) {
                    swal(result.message || "", result.description || "注册成功", "success");
                    router.push('/login')
                } else {
                    swal(result.message || "", result.description || "注册失败", "error");
                }
            } else {
                swal("哒咩!", "你的注册信息有误！", "error");
            }
        })
    }

    return {
        ruleFormRef,
        userRegisterForm,
        rules,
        submitForm
    }
})